﻿using RabbitMQ.Client.Events;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    public class WorkQueues
    {
        public static void Consume(string[] args)
        {
            var factory = new ConnectionFactory { HostName = "supplier.xl24h.cn", Port = 5672, UserName = "admin", Password = "das@123!", VirtualHost = "/" };
            using var connection = factory.CreateConnection();
            using var channel = connection.CreateModel();

            // 设置队列、消息过期时间
            var arguments = new Dictionary<string, object>();
            arguments.Add("x-expires", 1800000);
            arguments.Add("x-message-ttl", 60000);
            channel.QueueDeclare(queue: "task_queue-ttl",
                                 durable: true,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: arguments);

            Console.WriteLine(" [*] Waiting for messages.");

            // RabbitMQ 默认情况下使用轮循匀地调度消息，它不会查看消费者的未确认消息数量。它只是盲目地将每第 n 条消息发送给第 n 个消费者
            // 可以使用BasicQos prefetchCount=1
            channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                byte[] body = ea.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine($" [x] Received {message}");

                int dots = message.Split('.').Length - 1;
                Thread.Sleep(dots * 1000);

                Console.WriteLine(" [x] Done");

                channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
            };
            channel.BasicConsume(queue: "task_queue-ttl",
                                 autoAck: false,
                                 consumer: consumer);


            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
    }
}
